﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections;
using System.Collections.Generic;
using System.Threading;

namespace eHouse
{
    public class ServiceConnector
    {
        private AutoResetEvent wait = new AutoResetEvent(false);
        private AutoResetEvent removing;
        private object _countLock = new object();
        eHouseService.IeHouseServiceClient service = new eHouseService.IeHouseServiceClient();
        private string Sensor;
        public bool Error { get; private set; }
        private int initialCount;
        private int finalCount;

        public ServiceConnector()
        {
            service.ClearIrrigationRulesCompleted += OnClearRulesCompleted;
            service.ClearLightRulesCompleted += OnClearRulesCompleted;
            service.ClearTemperatureRulesCompleted += OnClearRulesCompleted;

            service.AddIrrigationRuleCompleted += OnAddRuleCompleted;
            service.AddLightRuleCompleted += OnAddRuleCompleted;
            service.AddTemperatureRuleCompleted += OnAddRuleCompleted;
        }

        private void OnAddRuleCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Cancelled || e.Error != null)
            {
                Error = true;
                return;
            }
            lock (_countLock)
            {
                finalCount++;
            }
            if (initialCount == finalCount)
            {
                wait.Set();
            }
        }

        private void OnClearRulesCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Cancelled || e.Error != null)
            {
                Error = true;
                return;
            }
            removing.Set();
        }

        public void SaveRules(string sensor)
        {
            Sensor = sensor;
            Error = false;
            using (removing = new AutoResetEvent(false))
            {
                switch (Sensor)
                {
                    case "Lights": service.ClearLightRulesAsync(); break;
                    case "Irrigation": service.ClearIrrigationRulesAsync(); break;
                    case "Temperature": service.ClearTemperatureRulesAsync(); break;
                    default: Error = true; return;
                }
                removing.WaitOne();
            }
            App.ConnectionManager.LoadRules(sensor, OnRulesReceived);
            wait.WaitOne();

        }

        private void OnRulesReceived(object sender, System.Net.Sockets.SocketAsyncEventArgs e)
        {
            if (e.SocketError != System.Net.Sockets.SocketError.Success)
            {
                Error = true;
                return;
            }
            new Thread(() =>
            {
                ICollection<Rule> rules = sender as ICollection<Rule>;
                initialCount = rules.Count;
                finalCount = 0;
                foreach (Rule rule in rules)
                {
                    switch (Sensor)
                    {
                        case "Lights": service.AddLightRuleAsync(rule.Formatted); break;
                        case "Irrigation": service.AddIrrigationRuleAsync(rule.Formatted); break;
                        case "Temperature": service.AddTemperatureRuleAsync(rule.Formatted); break;
                        default: Error = true; break;
                    }
                }
            }).Start();
        }
    }
}
